package GetPC

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

// GetPublicIP 获取服务器的公网 IP 地址
func GetPublicIP() (string, error) {
	// 使用 httpbin.org 提供的公网 IP 查询服务
	url := "https://httpbin.org/ip"

	// 发起 HTTP GET 请求
	resp, err := http.Get(url)
	if err != nil {
		return "", fmt.Errorf("failed to send request: %w", err)
	}
	defer resp.Body.Close()

	// 检查 HTTP 响应状态码
	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("failed to get public IP, status code: %d", resp.StatusCode)
	}

	// 读取响应内容
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", fmt.Errorf("failed to read response body: %w", err)
	}

	// 解析 JSON 响应
	var result map[string]interface{}
	if err := json.Unmarshal(body, &result); err != nil {
		return "", fmt.Errorf("failed to parse JSON response: %w", err)
	}

	// 提取 IP 地址
	ip, ok := result["origin"].(string)
	if !ok {
		return "", fmt.Errorf("failed to extract IP address from response")
	}

	return ip, nil
}
